<?php


namespace App\Services;


use App\Models\Config;
use PhpOffice\PhpWord\TemplateProcessor;

class EducationService
{

    public static $connectTimeout = 30;//30 second
    public static $readTimeout = 80;//80 second
    const IDURL='/api/educationVerification';
    const HOST='https://www.shanghaijushu.com';
    const ProjectId='20230722000001';
    const ProjectScert='4c74f0f67fba4efdaf7703b5ca563be1';
    const CheckPhone='/api/ispAuthenticationAggregation/twoName';

    public static function query($post=[])
    {
        $array=[];
        $array['appid']=self::ProjectId;
        $array['realName']=$post['cert_name'];
        $array['idNo']=strtoupper($post['cert_no']);
        $array['timestamp']=time();
        $array['serviceCode']='HRD024';
        $array['requestId']=uniqid();
        $signature=self::getApiSign($array,self::ProjectScert);
        $array['sign']=$signature;
        $array=json_encode($array);
        $res=http_post(self::HOST.self::IDURL,$array,array('Content-Type:application/json'));
        self::addLog('学历查询',$array,$res);
       return  json_decode($res,true);
    }

    //工作稳定性查询接口
    public static function stableWealthReport($post=[])
    {
        $array=[];
        $array['appid']=self::ProjectId;
        $array['name']=$post['cert_name'];
        $array['idNo']=$post['cert_no'];
        $array['timestamp']=time();
        $array['serviceCode']='SWR101';
        $array['requestId']=uniqid();
        $signature=self::getApiSign($array,self::ProjectScert);
        $array['sign']=$signature;
        $array=json_encode($array);
        $res=http_post('https://www.shanghaijushu.com/api/stableWealthReport',$array,array('Content-Type:application/json'));
        self::addLog('工作稳定性查询',$array,$res);
        return  json_decode($res,true);
    }

    //姓名与手机号是否一致
    public static function queryTwoName($post=[])
    {
        $array=[];
        $array['appid']=self::ProjectId;
        $array['realName']=$post['name'];
        $array['phone']=$post['phone'];
        $array['timestamp']=time();
        $array['serviceCode']='ISPTwoName';
        $array['requestId']=uniqid();
        $signature=self::getApiSign($array,self::ProjectScert);
        $array['sign']=$signature;
        $array=json_encode($array);
        $res=http_post('https://www.shanghaijushu.com/api/ispAuthenticationAggregation/twoName',$array,array('Content-Type:application/json'));
        self::addLog('手机二要素',$array,$res);
        return  $res;
    }

    /**
     * 探针
     * @param $post
     * @return mixed
     */
    public static function queryRiskProbe($post=[])
    {

        $file = './export/template_risk_probe.docx';

        $document = new TemplateProcessor($file);

        //2.插入数据
        //插入文字cert_name
        $document->setValue('cert_name', $post['cert_name']);
        $document->setValue('cert_no', $post['cert_no']);


        $mobile= substr_replace($post['mobile'],'****',3,4);

        $document->setValue('mobile', $mobile);
        $document->setValue('time', date('Y-m-d'));

        $cert_no = $post['cert_no'];

        $cert_no_start = substr($cert_no,0,6);

        $cert_no_end = substr($cert_no,12);

        $cert_no_2 = $cert_no_start.'******'.$cert_no_end;

        $document->setValue('cert_no', $cert_no_2);

        $orderId=$post['orderId'];
        //3.保存文件
        $fileName = $post['cert_name'].'orderRiskID.docx';

        // $file = './export/' . $fileName;

        $file = public_path('/export/') . $fileName;

        $document->saveAs($file);

//        chmod($file,0777);
//
//        return $file;
        $array=[];
        $array['appid']=self::ProjectId;
        $array['realName']=$post['cert_name'];
        $array['phone']=$post['mobile'];
        $array['idNo']=$post['cert_no'];
        $array['serviceCode']='RiskProbe';
        $array['timestamp']=time();
        $array['requestId']=uniqid();
        $array['accessoryUrl']='https://img.qianbaozuji.com/export/'.$fileName;
        $signature=self::getApiSign($array,self::ProjectScert);
        $array['sign']=$signature;
        $array=json_encode($array);
        $res=http_post('https://www.shanghaijushu.com/api/riskProbe',$array,array('Content-Type:application/json'));
        self::addLog('探针数据',$array,$res);
        return  $res;
    }

 public static function addLog($message,$request=[],$response=[]){
        $content = [
            'request'=>is_object($request) ? object_array($request) : $request,
            'response'=>is_object($response) ? object_array($response) : $response,
        ];
        \Illuminate\Support\Facades\Log::info($message,$content);
    }


    public static function getApiSign($params, $appkey) {
        ksort($params); $str = '';
        foreach ($params as $key => $val) { $str .= $key . $val; }
        $str .= $appkey;
        return md5($str);
    }

  public static  function HmacMd5($data,$key){

      $source = "appid=".$data['appid']."&idNo=".$data['idNo']."&realName=".$data['realName']."&serviceCode=".$data['serviceCode']."&timestamp=".$data['timestamp']."&requestId=".$data['requestId'].$key;
      return md5($source);

      foreach ($data as $k => $v){
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $data = self::formatBizQueryParaMap($Parameters, false);
        //签名步骤三：MD5加密
//        $String = md5($String);

        $data =utf8_encode($data);
        $b = 64; // byte length for md5
        $key = pack("H*",md5($key));
        $key = str_pad($key, $b, chr(0x00));
        $ipad = str_pad('', $b, chr(0x36));
        $opad = str_pad('', $b, chr(0x5c));
        $k_ipad = $key ^ $ipad ;
        $k_opad = $key ^ $opad;
        $encodeStr=md5($k_opad .pack("H*",md5($k_ipad . $data)));
      return strtoupper(bin2hex($encodeStr));

    }

    protected static function getSign($Obj){
        foreach ($Obj as $k => $v){
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = self::formatBizQueryParaMap($Parameters, true);
//        dd($String);
        //签名步骤三：MD5加密
//        $String = md5($String);
        $signature = hash_hmac("md5", utf8_encode($String), utf8_encode(self::ProjectScert), true);
        var_dump($signature);
        $signature = strtoupper(bin2hex($signature));
        //签名步骤四：
        return $signature;
    }

    /*
 *排序并格式化参数方法，签名时需要使用
 */
    protected  static function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v)
        {
            if($urlencode)
            {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar='';
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }


}
